package com.drojian.demo1.myself;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.drojian.demo.R;

//自定义属性
public class MyPropertyAttributeView extends View {

    private int myAge;
    private String myName;
    private Bitmap myBg;



    public MyPropertyAttributeView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        //获取属性的三种方式
        //1.用命名空间获取
        String age = attrs.getAttributeValue("http://schemas.android.com/apk/res-auto","my_age");
        String name = attrs.getAttributeValue("http://schemas.android.com/apk/res-auto","my_name");
        String my_bg = attrs.getAttributeValue("http://schemas.android.com/apk/res-auto","my_bg");

        //2.遍历属性集合
        for (int i = 0; i < attrs.getAttributeCount(); i++) {
            //System.out.println(attrs.getAttributeName(i)+""+attrs.getAttributeValue(i));
        }

        //3.使用系统工具，获取属性
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.MyPropertyAttributeView);
        for (int i = 0; i < typedArray.getIndexCount(); i++) {
            int index = typedArray.getIndex(i);
            if(index == R.styleable.MyPropertyAttributeView_my_age){
                 myAge = typedArray.getInt(index,0);
            }else if(index == R.styleable.MyPropertyAttributeView_my_name){
                myName = typedArray.getString(index);
            }else if(index == R.styleable.MyPropertyAttributeView_my_bg){
                Drawable drawable = typedArray.getDrawable(index);
                BitmapDrawable bitmapDrawable = (BitmapDrawable)drawable;
                myBg = bitmapDrawable.getBitmap();

            }

        }
    }
    @Override
    protected void onDraw(@NonNull Canvas canvas) {
        super.onDraw(canvas);
        Paint paint = new Paint();
        paint.setTextSize(60);
        canvas.drawText("自定义属性name为："+myName,TEXT_ALIGNMENT_CENTER,300,paint);
        canvas.drawText("自定义属性age为："+myAge,TEXT_ALIGNMENT_CENTER,400,paint);
        canvas.drawBitmap(myBg,200,550,paint);
    }
}
